import { getToken } from './util'
import { BASE_URL } from './consts'

/**
 * http request
 * @param {string} url 请求地址
 * @param {object} options { method, body }
 */
export default function request(url, options = {}) {
  const token = getToken()
  const header = {
    'Authorization': 'Bearer ' + token
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + url,
      header,
      method: options.method ? options.method.toUpperCase() : 'GET',
      data: options.body,
      success: ({ statusCode, data }) => {
        if (statusCode >= 200 && statusCode < 300) {
          resolve(data)
        } else {
          reject(data)
        }
      },
      fail: (error) => {
        reject(error)
        console.error('error!', error)
      }
    })
  })
}